<!-- 订单详情 -->
<template>
	<view class="container flex_C">
		<FeNavbar title="订单详情" />

		<scroll-view class="scroll" scroll-y="true">
			<view class="order-status" v-if="orderDatas.isOver">该笔订单已结束</view>
			<view class="wrap1" v-if="orderDatas">
				<view class="title">{{orderDatas.strategyName || "--"}}</view>
				<view class="flex">
					<view class="flex_1">
						<view class="value">{{orderDatas.maxDrawdown || 0}}%</view>
						<view class="label">最大回撤</view>
					</view>
					<view class="flex_1">
						<view class="flexV">
							<view class="value">{{orderDatas.leverageMultiplier || 0}}X</view>
							<image class="wenhao" @click="$refs.explain.show('杠杆说明')" src="/static/mine/wenhao.png"
								mode="aspectFill"></image>
						</view>
						<view class="label">杠杆</view>
					</view>
				</view>
				<view class="times-row">
					<view class="order-time">购买账号：{{orderDatas.subAccountName || "--"}}</view>
					<view class="order-time create-time">
						创建时间：{{orderDatas.createTime ? momentFormat(orderDatas.createTime) : "--"}}</view>
				</view>
			</view>
			<view class="wrap2">
				<view class="tab_wrap flexV_sb">
					<view class="tab_item flexHV" :class="[tabIndex==1?'on':'']" @click="days=7;tabIndex=1">7天</view>
					<view class="tab_item flexHV" :class="[tabIndex==2?'on':'']" @click="days=30;tabIndex=2">30天</view>
					<view class="tab_item flexHV" :class="[tabIndex==3?'on':'']" @click="days=60;tabIndex=3">
						<template v-if="tabIndex!==3">
							自定义
						</template>
						<input class="input" type="digit" v-model="customDays" v-else @input="customDaysInput" />
					</view>
				</view>
				<view class="earnings_wrap">
					<view class="day_wrap">
						<view class="sub">每日收益</view>
						<template v-if="JSON.stringify(everydayProfit) != '{}'">
							<view class="earnings" v-if="everydayProfit.profit>=0">+${{everydayProfit.profit|| 0}}
							</view>
							<view class="earnings" v-else>${{everydayProfit.profit}}</view>
						</template>
						<template v-else>
							<view class="earnings">$0</view>
						</template>
					</view>
					<FeChart :option="earningsOption" v-on:chartClick="earningsChartClick" idName="earnings_chart"
						height="440rpx">
					</FeChart>
				</view>
				<view class="yield_wrap">
					<view class="day_wrap">
						<view class="flexV">
							<view class="sub">累计收益率</view>
							<image class="wenhao" @click="handleItemEvent({action:'syl_tip'})"
								src="/static/mine/wenhao.png" mode=""></image>
						</view>
						<view class="date">
							{{returnRateIndex>-1?returnRate.strategy.returns[returnRateIndex].date: '--'}}
						</view>
						<view class="flexV">
							<view class="flex_1">
								<view class="earnings">
									<template v-if="returnRateIndex>-1">
										<template v-if="returnRate.strategy.returns[returnRateIndex].returnRate>0">
											+{{returnRate.strategy.returns[returnRateIndex].returnRate}}%
										</template>
										<template v-else>
											{{returnRate.strategy.returns[returnRateIndex].returnRate}}%
										</template>
									</template>
								</view>
								<view class="legend flexV">
									<view class="dian" style="--color:#FA8C4E"></view>
									<text class="label">累计收益率</text>
								</view>
							</view>
							<view class="flex_1">
								<view class="earnings">
									<template v-if="returnRateIndex>-1">
										<template v-if="returnRate.currencies[0].returns[returnRateIndex].returnRate>0">
											+{{returnRate.currencies[0].returns[returnRateIndex].returnRate}}%
										</template>
										<template v-else>
											{{returnRate.currencies[0].returns[returnRateIndex].returnRate}}%
										</template>
									</template>
								</view>
								<view class="legend flexV">
									<view class="dian" style="--color:#5FA7F0"></view>
									<text class="label">
										累计{{returnRateIndex>-1?returnRate.currencies[0].name:'--'}}趋势
									</text>
								</view>
							</view>
						</view>
					</view>
					<FeChart :option="yieldOption" idName="yield_chart" v-on:chartClick="yieldChartClick"
						height="390rpx">
					</FeChart>
				</view>
			</view>
			<view class="bottom-tip-wrap">
				<view class="tip-item flexV_sb">
					<view class="title">开仓保证金</view>
					<view class="money-value">
						<template v-if="orderDatas">
							{{orderDatas.deposit || 0}} USDT
						</template>
					</view>
					<image class="wenhao" @click="$refs.explain.show('开仓保证金')" src="/static/mine/wenhao.png"
						mode="aspectFill"></image>
				</view>
				<view class="tip-item flexHV">
					<view class="title">预估服务费</view>
					<view class="money-value">
						<template v-if="orderDatas">
							{{orderDatas.charge || 0}} USDT
						</template>
					</view>
					<image class="wenhao" @click="$refs.explain.show('预估服务费')" src="/static/mine/wenhao.png"
						mode="aspectFill"></image>
				</view>
			</view>
			<view class="hr"></view>

			<!-- 一键平仓 -->
			<onKeyClearPanel ref="refOnKeyClearPanel" @complete="refresh" />

		</scroll-view>

		<view v-if="(orderDatas && !orderDatas.isOver) && isLoad" class="btn_wrap flexV_sb">
			<view class="btn flexHV" @click="handleItemEvent({action:'onKeyClear'})">一键平仓</view>
		</view>

		<Explain ref="explain" />
	</view>
</template>

<script>
	import FeNavbar from '@/components/FeNavbar/FeNavbar.vue'
	import FeChart from '@/components/FeChart/index.vue'
	import onKeyClearPanel from '@/components/onKeyClearPanel/onKeyClearPanel.vue'
	import Explain from '@/components/explain/explain.vue'
	import {
		orderDetail,
		orderProfit,
		orderReturnRate
	} from "@/api/order.js"

	export default {
		components: {
			FeNavbar,
			FeChart,
			onKeyClearPanel,
			Explain
		},
		data() {
			return {
				orderDatas: {},
				tabIndex: 1,
				days: 7,
				customDays: 60,
				returnRate: {},
				returnRateIndex: -1,
				profit: [],
				everydayProfit: {},
				earningsOption: {},
				yieldOption: {},
				option: null,

				time: null,
				time2: null,
				isLoad: false
			}
		},
		watch: {
			days: {
				handler(val) {
					if (Number(val) == NaN) return
					if (val < 2) {
						uni.showToast({
							icon: 'none',
							title: '天数不能小于2天'
						});
						return
					}
					this.getProfit(val);
					this.getReturnRate(val);
				}
			}
		},
		onLoad(option) {
			console.log("onload--", option)
			this.option = option;
			this.refresh()
		},
		methods: {
			refresh() {
				this.reqOrderDetail();
				this.getProfit(this.days);
				this.getReturnRate(this.days);
			},
			reqOrderDetail() {
				orderDetail(this.option.id).then((result) => {
					this.orderDatas = {
						...this.orderDatas,
						...result.data
					};
					this.isLoad = true;
				}).catch(() => {
					console.log("详情请求失败---")
				});
			},

			// 获取订单收益
			async getProfit(days) {
				uni.showLoading({
					title: "加载中..."
				})
				const res = await orderProfit(this.option.id, {
					days
				})
				if (res.code === 200) {

					// 这里需要加上这个判断，不然空数组往下执行会报错，影响"一键平仓"按钮显隐。
					// [Vue warn]: Error in render: "TypeError: Cannot read property 'profit' of undefined"
					if (this.isEmpty(res.data.returns)) return

					this.$nextTick(() => {

						const source = res.data.returns.reverse();
						const seriesData = source.map(item => item.profit)

						this.profit = source;
						this.everydayProfit = source[source.length - 1]
						const max = Math.floor(Math.max(...seriesData));
						const min = Math.ceil(Math.min(...seriesData));
						this.earningsOption = {
							color: ['#FFE269'],
							grid: {
								top: uni.upx2px(32),
								left: 0,
								bottom: 0,
								right: uni.upx2px(32),
								containLabel: true
							},
							xAxis: {
								type: 'category',
								boundaryGap: false,
								data: source.map(item => item.date.slice(5)),
								axisLine: {
									show: false
								},
								axisTick: {
									show: false
								},
								splitLine: {
									show: false
								},
								axisLabel: {
									showMaxLabel: true
								}
							},
							yAxis: {
								type: 'value',
								min: min - 2 - Math.abs(min * .2),
								max: max + max * .2 + 2,
								splitLine: {
									show: true
								}
							},
							series: [{
								data: seriesData,
								type: 'line',
								lineStyle: {
									width: 2
								},
								markPoint: {
									data: [{
											type: 'max',
											name: 'max',
											itemStyle: {
												color: "rgba(255, 226, 105, 0)"
											},
											label: {
												// formatter: '+${c}',
												formatter: (vals) => {
													if (vals.value < 0) {
														return `-$${Math.abs(vals.value)}`
													}
													return '+$' + vals.value
												},
												color: '#D6A909',
												fontSize: uni.upx2px(26),
												fontWeight: 500,
												offset: [0, 15]
											}
										},
										{
											type: 'min',
											name: 'Min',
											itemStyle: {
												color: "rgba(255, 226, 105, 0)"
											},
											label: {
												// formatter: '+${c}',
												formatter: (vals) => {
													if (vals.value < 0) {
														return `-$${Math.abs(vals.value)}`
													}
													return '+$' + vals.value
												},
												color: '#D6A909',
												fontSize: uni.upx2px(26),
												fontWeight: 500,
												offset: [0, 10]
											}
										}
									]
								},
								areaStyle: {
									color: 'rgba(255, 226, 105, 0.20)',
								},
							}]
						}
					})
				}
			},
			// 获取订单收益率
			async getReturnRate(days) {
				uni.showLoading({
					title: "加载中..."
				})
				const res = await orderReturnRate(this.option.id, {
					days
				})
				if (res.code === 200) {
					this.returnRate = res.data;
					try {
						const returns = res.data.strategy.returns.reverse();
						this.returnRateIndex = returns.length - 1
						const currenciesReturns = res.data.currencies[0].returns.reverse();
						const serverData1 = returns.map((item) => item.returnRate);
						const serverData2 = currenciesReturns.map((item) => item.returnRate);
						const max = Math.floor(Math.max(...[...serverData1, ...serverData2]));
						const min = Math.ceil(Math.min(...[...serverData1, ...serverData2]));
						this.yieldOption = {
							color: ['#FFE269', '#5FA7F0'],
							grid: {
								top: 6,
								left: 0,
								bottom: 0,
								right: uni.upx2px(32),
								containLabel: true
							},
							xAxis: {
								type: 'category',
								boundaryGap: false,
								data: returns.map(item => item.date.slice(5)),
								axisLine: {
									show: false
								},
								axisTick: {
									show: false
								},
								splitLine: {
									show: false
								},
								axisLabel: {
									showMaxLabel: true
								}
							},
							yAxis: {
								// type: 'value',
								// min: min - 2 - Math.abs(min*.2),
								// max: max + max*.2+2,
								// splitLine: {
								// 	show: true
								// },
								splitNumber: 3,
								type: 'value',
								min: min - 2 - Math.abs(min * .2),
								max: max + max * .2 + 2,
								splitLine: {
									show: true
								}
							},
							series: [{
								data: serverData1,
								type: 'line',
								lineStyle: {
									width: 2
								},
							}, {
								data: serverData2,
								type: 'line',
								lineStyle: {
									width: 2
								},
							}]
						}
					} catch (e) {
						console.log(e, '错误')
						//TODO handle the exception
					}
				}
			},

			// 获取收益和收益率
			// async reqProfit() {
			// 	let params = {}
			// 	params["days"] = this.selectDay;

			// 	const result = await orderProfit(this.option.id, params);
			// 	const result2 = await orderReturnRate(this.option.id, params);
			// },

			handleItemEvent(vals) {
				const {
					action,
					day,
					index
				} = vals;
				switch (action) {
					case "onKeyClear": // 一键平仓
						this.$refs.refOnKeyClearPanel.show({
							level: "order",
							orderId: Number(this.option.id)
						});
						break;

					case "gg_tip": // 杠杆
						uni.showModal({
							title: "杠杆",
							content: "杠杆说明",
							showCancel: false,
							confirmText: "知道了"
						})
						break;

					case "syl_tip": // 累计收益率
						uni.showModal({
							title: "累计收益率",
							content: "累计收益率说明",
							showCancel: false,
							confirmText: "知道了"
						})
						break;

					case "kc_tip": // 开仓保证金
						uni.showModal({
							title: "开仓保证金",
							content: "开仓保证金说明",
							showCancel: false,
							confirmText: "知道了"
						})
						break;

					case "yj_tip": // 预估服务费
						uni.showModal({
							title: "预估服务费",
							content: "开仓后预计平台收取的服务费",
							showCancel: false,
							confirmText: "知道了"
						})
						break;
					case "dayChange": // 切换天数
						break;
				}
			},

			earningsChartClick(val) {
				this.everydayProfit = this.profit[val.xIndex]
				this.earningsOption = {
					...this.earningsOption,
					series: [{
						...this.earningsOption.series[0],
						markLine: {
							symbol: 'none',
							lineStyle: {
								color: 'rgba(255, 226, 105, 0.70)',
								type: 'solid'
							},
							label: {
								show: false
							},
							data: [{
								xAxis: val.xIndex,
								symbol: 'none'
							}, {
								yAxis: this.profit[val.xIndex].profit,
								symbol: 'none'
							}],
							animation: true,
							animationDuration: 500

						},
					}]
				};
				if (this.time) {
					clearTimeout(this.time)
				}
				this.time = setTimeout(() => {
					this.time = null
					this.earningsOption = {
						...this.earningsOption,
						series: [{
							...this.earningsOption.series[0],
							markLine: {
								data: []
							}
						}]
					};
				}, 3000)
			},
			customDaysInput(e) {
				let {
					value
				} = e.detail;
				value = value.replace('.', '');
				value = Number(value)
				this.$nextTick(() => {
					this.customDays = value
					this.days = value
				})
			},
			yieldChartClick(val) {
				this.returnRateIndex = val.xIndex;
				this.yieldOption = {
					...this.yieldOption,
					series: [{
						...this.yieldOption.series[0],
						markLine: {
							symbol: 'none',
							lineStyle: {
								color: '#FFE269',
								type: 'solid'
							},
							label: {
								show: false
							},
							data: [{
								xAxis: val.xIndex,
							}, {
								yAxis: this.yieldOption.series[0].data[val.xIndex],
							}, {
								yAxis: this.yieldOption.series[1].data[val.xIndex],
								lineStyle: {
									color: '#5FA7F0',
								}
							}],
							animationDuration: 500
						},
					}, {
						...this.yieldOption.series[1],
					}]
				}
				if (this.time2) {
					clearTimeout(this.time2)
				}
				this.time2 = setTimeout(() => {
					this.time2 = null
					this.yieldOption = {
						...this.yieldOption,
						series: [{
							...this.yieldOption.series[0],
							markLine: {
								data: []
							}
						}, {
							...this.yieldOption.series[1],
						}]
					}
				}, 3000)
			},
		}
	}
</script>

<style scoped lang="scss">
	.container {
		height: 100vh;
		background-color: #F5F7F8;

		.scroll {
			flex: 1;
			height: 0;
			padding-bottom: 1px;
		}

		.wenhao {
			width: 32rpx;
			height: 32rpx;
			margin-left: 12rpx;
		}

		.order-status {
			height: 80rpx;
			line-height: 80rpx;
			background-color: #ECF0F4;
			text-align: center;
			font-size: 28rpx;
			color: #A6ACB4;
		}

		.wrap1 {
			background-color: #fff;
			padding: 32rpx;

			.title {
				font-weight: 600;
				font-size: 40rpx;
				color: #26282B;
				margin-bottom: 24rpx;
			}

			.value {
				font-weight: bold;
				font-size: 36rpx;
				color: #26282B;
			}

			.label {
				font-weight: 400;
				font-size: 24rpx;
				color: #7B828A;
				margin-top: 4rpx;
			}

			.icon {
				width: 32rpx;
				height: 32rpx;
				margin-left: 12rpx;
			}

			.times-row {
				border-top: 1px dashed #A6ACB4;
				margin-top: 32rpx;
				padding-top: 24rpx;

				.order-time {
					font-size: 24rpx;
					color: #A6ACB4;
					line-height: 28rpx;
				}

				.create-time {
					padding-top: 8rpx;
				}
			}
		}

		.wrap2 {
			background-color: #fff;
			margin-top: 24rpx;
			padding: 32rpx;

			.tab_wrap {
				.tab_item {
					width: 214rpx;
					height: 56rpx;
					background: #EEF1F6;
					border-radius: 8rpx;
					font-weight: 400;
					font-size: 26rpx;
					color: #7B828A;
					transition: all .3s;

					&.on {
						background-color: #FFE269;
						color: #26282B;
					}

					.input {
						width: 100%;
						height: 100%;
						font-size: 26rpx;
						color: #26282B;
						text-align: center;
					}
				}
			}

			.earnings_wrap {
				margin-top: 32rpx;
			}

			.day_wrap {
				margin-bottom: 24rpx;

				.sub {
					font-weight: 600;
					font-size: 28rpx;
					color: #26282B;
				}

				.date {
					font-weight: 400;
					font-size: 24rpx;
					color: #A6ACB4;
					margin-top: 4rpx;
				}

				.earnings {
					font-weight: bold;
					font-size: 44rpx;
					color: #06B070;
					margin-top: 20rpx;
				}


				.legend {
					margin-top: 8rpx;

					.dian {
						width: 12rpx;
						height: 12rpx;
						border-radius: 50%;
						background-color: var(--color);
					}

					.label {
						font-weight: 400;
						font-size: 24rpx;
						color: #7B828A;
						margin-left: 8rpx;
					}
				}
			}

			.yield_wrap {
				margin-top: 48rpx;
			}
		}

		.bottom-tip-wrap {
			background-color: #ffffff;
			padding: 0 32rpx;
			margin-top: 24rpx;

			.tip-item {
				height: 108rpx;
				line-height: 108rpx;

				.money-value {
					flex: 1;
					text-align: right;
				}

				.wenhao {
					margin-left: 20rpx;
				}
			}

			.tip-item:last-child {
				border-top: 1px solid #DBE0E6;
			}
		}

		.hr {
			height: 100rpx;
		}

		.btn_wrap {
			padding: 0 32rpx;
			height: 116rpx;
			background-color: #fff;
			border-top: 1px solid #DBE0E6;

			.btn {
				flex: 1;
				height: 88rpx;
				background-color: #FFE269;
				color: #26282B;
				border-radius: 12rpx;
				font-weight: 600;
				font-size: 30rpx;
			}
		}
	}
</style>